package com.zh.common.ktx

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.transition.Transition
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityOptionsCompat
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter
import com.zh.common.utils.ActManager
import com.zh.common.utils.DoubleUtils
import com.zh.common.utils.OnTransitionListener

class IntentKtx {
}

/**
 * activity注册回调
 */
fun ComponentActivity.registerForResult(callBack: (ActivityResult) -> Unit): ActivityResultLauncher<Intent> {
    return registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        callBack.invoke(it)
    }
}

/**
 * fragment注册回调
 */
fun Fragment.registerForResult(callBack: (ActivityResult) -> Unit): ActivityResultLauncher<Intent> {
    return registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        callBack.invoke(it)
    }
}

/**
 * 跳转页面
 */
fun ActivityResultLauncher<Intent>.launch(
    context: Context, toClass: Class<*>, intentFun: (Intent.() -> Unit)? = null
) {
    launch(Intent(context, toClass).apply { intentFun?.invoke(this) })
}


/**
 * 设置回调数据
 */
fun Activity.setResult(intentFun: (Intent.() -> Unit)? = null) {
    setResult(Activity.RESULT_OK, Intent().apply { intentFun?.invoke(this) })
}

/**
 * Intent(Context) 跳转页面
 * @param singleClickTo = true时 不要在扩展函数 clickSingleListener 中使用
 */
fun Context.gotoAct(
    clazz: Class<*>, singleClickTo: Boolean = false, intentFun: (Intent.() -> Unit)? = null
) {
    if (singleClickTo and DoubleUtils.isFastDoubleClick()) return
    startActivity(Intent(this, clazz).apply { intentFun?.invoke(this) })
}

fun Context.gotoActDocument(
    clazz: Class<*>, tag: String, singleClickTo: Boolean = false,
    intentFun: (Intent.() -> Unit)? = null
) {
    if (singleClickTo and DoubleUtils.isFastDoubleClick()) return
    //绑定唯一标识 tag，存在 则根据 taskId 移动到前台
    if (ActManager.getInstance().isActive(tag)) {
        ActManager.getInstance().resumeActivity(tag)
    } else {
        val intent = Intent(this, clazz).apply {
            //打开多任务窗口 flags
            addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
            addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
            putExtra("tag", tag)
            intentFun?.invoke(this)
        }
        startActivity(intent)
    }
}

/**
 * Intent(Fragment) 跳转页面
 * @param singleClickTo = true时 不要在扩展函数 clickSingleListener 中使用
 */
fun Fragment.gotoAct(
    clazz: Class<*>, singleClickTo: Boolean = false, intentFun: (Intent.() -> Unit)? = null
) {
    if (singleClickTo and DoubleUtils.isFastDoubleClick()) return
    startActivity(Intent(context, clazz).apply { intentFun?.invoke(this) })
}

/**
 * 阿里路由 跳转页面
 * @param singleClickTo = true时 不要在扩展函数 clickSingleListener 中使用
 */
fun gotoAct(url: String, singleClickTo: Boolean = false, intentFun: (Bundle.() -> Unit)? = null) {
    if (singleClickTo and DoubleUtils.isFastDoubleClick()) return
    ARouter.getInstance().build(url).apply { intentFun?.invoke(this.extras) }.navigation()
}

/**
 * Intent(Activity) 跳转页面，与initAnimation一起使用
 * @param singleClickTo = true时 不要在扩展函数 clickSingleListener 中使用
 * @param target 需要实现动画的View
 */
fun Activity.gotoActAnimation(
    clazz: Class<*>, target: View, singleClickTo: Boolean = false,
    intentFun: (Intent.() -> Unit)? = null
) {
    if (singleClickTo and DoubleUtils.isFastDoubleClick()) return
    val pair = androidx.core.util.Pair(target, "transition")
    val actOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(this, pair)
    startActivity(
        Intent(this, clazz).apply { intentFun?.invoke(this) }, actOptions.toBundle()
    )
}

/**
 * Intent(Fragment) 跳转页面，与initAnimation一起使用
 * @param singleClickTo = true时 不要在扩展函数 clickSingleListener 中使用
 * @param target 需要实现动画的View
 */
fun Fragment.gotoActAnimation(
    clazz: Class<*>, target: View, singleClickTo: Boolean = false,
    intentFun: (Intent.() -> Unit)? = null
) {
    if (singleClickTo and DoubleUtils.isFastDoubleClick()) return
    val pair = androidx.core.util.Pair(target, "transition")
    val actOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(requireActivity(), pair)
    startActivity(
        Intent(context, clazz).apply { intentFun?.invoke(this) }, actOptions.toBundle()
    )
}

/**
 * 在接收跳转的Activity中初始化
 * @param target 需要展示动画的View
 * @param callBack 动画结束监听
 */
fun Activity.initAnimation(target: View, callBack: () -> Unit? = { }) {
    postponeEnterTransition()
    ViewCompat.setTransitionName(target, "transition")
    window?.sharedElementEnterTransition?.addListener(object : OnTransitionListener() {
        override fun onTransitionEnd(transition: Transition?) {
            callBack.invoke()
            transition?.removeListener(this)
        }
    })
    startPostponedEnterTransition()
}

/**
 * 访问公有文件权限，否则获取不到系统裁剪之后的图片
 * Android 11 以上需要特殊处理，不然系统裁剪等功能获取不到图片
 */
fun ActivityResultLauncher<Intent>.gotoFileAndroid11(
    activity: Activity, callBack: () -> Unit = {}
) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R || Environment.isExternalStorageManager()) {
        callBack.invoke()
    } else {
        val builder = AlertDialog.Builder(activity)
            .setMessage("本程序需要您同意允许访问所有文件权限")
            .setPositiveButton("确定") { _, _ ->
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.data = Uri.parse("package:${activity.packageName}")
                this.launch(intent)
            }
        builder.show()
    }
}
